//
//  MAVipViewController.m
//  MateAdv
//
//  Created by 茶 on 2023/9/14.
//

#import "CAVipViewController.h"
#import "CAIAPTool.h"
#import "CAVipSubView.h"

@interface CAVipViewController ()

@property (nonatomic, strong) NSArray *dataSource;
@property (nonatomic, strong) NSMutableArray *itemArray;
@property (nonatomic, assign) NSUInteger selectIndex;
@property (nonatomic, strong) UIButton *checkBtn;

@end

@implementation CAVipViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initInterface];
    [self initDataSource];
}

- (void)initInterface {
    self.title = @"开通会员";
    self.view.backgroundColor = HexColor(@"#F8F8F8");
    [self initTipView];
}

- (void)initTipView {
    UIView *tipView = [UIView new];
    tipView.backgroundColor = UIColor.whiteColor;
    tipView.layer.cornerRadius = CARatioWidth(10);
    [self.view addSubview:tipView];
    [tipView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.ca_offset(15);
        make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop).ca_offset(15);
        make.right.ca_offset(-15);
        make.height.ca_offset(94);
    }];
    
    UIImageView *imgView1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Vip_1"]];
    [tipView addSubview:imgView1];
    [imgView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.ca_offset(19);
        make.left.ca_offset(40);
    }];
    
    UILabel *label1 = [UILabel new];
    label1.text = @"随心拍摄复古照片和视频";
    label1.font = CAFontScaleRegular(14);
    label1.textColor = HexColor(@"#29282A");
    [tipView addSubview:label1];
    [label1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(imgView1);
        make.left.ca_offset(72);
    }];
    
    UIImageView *imgView2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Vip_2"]];
    [tipView addSubview:imgView2];
    [imgView2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.ca_offset(54);
        make.left.ca_offset(40);
    }];
    
    UILabel *label2 = [UILabel new];
    label2.text = @"上传本地图片，使用滤镜";
    label2.font = CAFontScaleRegular(14);
    label2.textColor = HexColor(@"#29282A");
    [tipView addSubview:label2];
    [label2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(imgView2);
        make.left.ca_offset(72);
    }];
    
    UIButton *payBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [payBtn setBackgroundColor:HexColor(@"#29282A")];
    [payBtn setTitle:@"立即支付" forState:UIControlStateNormal];
    [payBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [payBtn.titleLabel setFont:CAFontScaleRegular(16)];
    [payBtn addTarget:self action:@selector(confirmEvent) forControlEvents:UIControlEventTouchUpInside];
    payBtn.layer.cornerRadius = CARatioWidth(24.5);
    [self.view addSubview:payBtn];
    [payBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop).ca_offset(279);
        make.left.ca_offset(15);
        make.right.ca_offset(-15);
        make.height.ca_offset(49);
    }];
    
    UIButton *checkBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [checkBtn setImage:[UIImage imageNamed:@"Vip_Agree_0"] forState:UIControlStateNormal];
    [checkBtn setImage:[UIImage imageNamed:@"Vip_Agree_1"] forState:UIControlStateSelected];
    [checkBtn addTarget:self action:@selector(checkEvent:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:checkBtn];
    [checkBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop).ca_offset(343);
        make.left.ca_offset(30);
    }];
    _checkBtn = checkBtn;
    
    UILabel *label = [UILabel new];
    label.text = @"我已阅读";
    label.font = CAFontScaleRegular(12);
    label.textColor = HexColor(@"#666666");
    [self.view addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(checkBtn);
        make.left.mas_equalTo(checkBtn.mas_right).ca_offset(5);
    }];
    
    UIButton *userBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [userBtn.titleLabel setFont:CAFontScaleRegular(12)];
    [userBtn setTitle:@"《会员协议》" forState:UIControlStateNormal];
    [userBtn addTarget:self action:@selector(userEvent) forControlEvents:UIControlEventTouchUpInside];
    [userBtn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
    [self.view addSubview:userBtn];
    [userBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(checkBtn);
        make.left.mas_equalTo(label.mas_right);
    }];
    
    UILabel *andLabel = [UILabel new];
    andLabel.text = @"和";
    andLabel.font = CAFontScaleRegular(12);
    andLabel.textColor = HexColor(@"#666666");
    [self.view addSubview:andLabel];
    [andLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(checkBtn);
        make.left.mas_equalTo(userBtn.mas_right);
    }];
    
    UIButton *privacyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [privacyBtn.titleLabel setFont:CAFontScaleRegular(12)];
    [privacyBtn setTitle:@"《自动续费协议》" forState:UIControlStateNormal];
    [privacyBtn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
    [privacyBtn addTarget:self action:@selector(privacyEvent) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:privacyBtn];
    [privacyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(checkBtn);
        make.left.mas_equalTo(andLabel.mas_right);
    }];
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"恢复购买" style:UIBarButtonItemStylePlain target:self action:@selector(resumeEvent)];
    [rightItem setTitleTextAttributes:@{NSFontAttributeName : CAFontScaleRegular(16)} forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = rightItem;
}

- (void)initDataSource {
    if ([CAIAPTool shareTool].products.count > 0) {
        [self initProductView];
    } else {
        CAWeakify(self);
        [SVProgressHUD show];
        [[CAIAPTool shareTool] ca_requestAllProductWithCompletion:^(BOOL isSuccess, NSString * _Nonnull msg) {
            dispatch_async(dispatch_get_main_queue(), ^{
                CAStrongify(self);
                [SVProgressHUD dismiss];
                if (isSuccess) {
                    [self initProductView];
                } else {
                    [self.view makeToast:msg];
                }
            });
        }];
    }
}

- (void)initProductView {
    if (_itemArray) {
        return;
    }
    _selectIndex = 0;
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:[CAIAPTool shareTool].products.count];
    for (SKProduct *product in [CAIAPTool shareTool].products) {
        if ([product.productIdentifier isEqualToString:@"camera_year"]) {
            [array insertObject:product atIndex:0];
            break;
        }
    }
    
    for (SKProduct *product in [CAIAPTool shareTool].products) {
        if ([product.productIdentifier isEqualToString:@"camera_month"]) {
            [array addObject:product];
            break;
        }
    }
    
    for (SKProduct *product in [CAIAPTool shareTool].products) {
        if ([product.productIdentifier isEqualToString:@"camera_season"]) {
            [array addObject:product];
            break;
        }
    }
    
    self.dataSource = [array copy];
    
    CAWeakify(self);
    _itemArray = [NSMutableArray arrayWithCapacity:_dataSource.count];
    for (int i = 0; i < _dataSource.count; i++) {
        SKProduct *product = _dataSource[i];
        CAVipSubView *subView = [CAVipSubView new];
        subView.title = product.localizedTitle;
        subView.price = product.price.stringValue;
        subView.tag = i;
        if (i == 0) {
            subView.selected = YES;
        } else {
            subView.selected = NO;
        }
        subView.selectBlock = ^(NSUInteger tag) {
            CAStrongify(self);
            [self selectItemEvent:tag];
        };
        [self.view addSubview:subView];
        [_itemArray addObject:subView];
        [subView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop).ca_offset(124);
            make.height.ca_offset(105);
        }];
    }
    [_itemArray mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedItemLength:CARatioWidth(105) leadSpacing:CARatioWidth(15) tailSpacing:CARatioWidth(15)];
    
}

- (void)selectItemEvent:(NSUInteger)tag {
    for (CAVipSubView *view in _itemArray) {
        view.selected = NO;
    }
    CAVipSubView *view = _itemArray[tag];
    view.selected = YES;
    _selectIndex = tag;
}

- (void)checkEvent:(UIButton *)button {
    button.selected = !button.isSelected;
}

- (void)userEvent {
    NSURL *url = [NSURL URLWithString:kAgreement];
    if ([[UIApplication sharedApplication] canOpenURL:url]){
        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
    }
}

- (void)privacyEvent {
    NSURL *url = [NSURL URLWithString:kPayAgreement];
    if ([[UIApplication sharedApplication] canOpenURL:url]){
        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
    }
}

- (void)confirmEvent {
    if (!_checkBtn.isSelected) {
        [self.view makeToast:@"请同意协议后继续购买"];
        return;
    }
    CAWeakify(self);
    [SVProgressHUD showWithStatus:@"正在购买中..."];
    SKProduct *product = self.dataSource[_selectIndex];
    [[CAIAPTool shareTool] ca_buyProductWithId:product.productIdentifier completion:^(BOOL succed, NSString * _Nonnull msg, SKPaymentTransaction *transaction) {
        dispatch_async(dispatch_get_main_queue(), ^{
            CAStrongify(self);
            [SVProgressHUD dismiss];
            [kKeyWindow makeToast:msg];
            if (succed) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
                });
            }
        });
    }];
}

- (void)resumeEvent {
    if (kUserModel.vipStatus> 0) {
        [self.view makeToast:@"您已经是VIP,无需恢复购买"];
    } else {
        CAWeakify(self);
        [[CAIAPTool shareTool] ca_restoreProductWithCompletion:^(BOOL isSuccess, NSString * _Nonnull msg) {
            dispatch_async(dispatch_get_main_queue(), ^{
                CAStrongify(self);
                [kKeyWindow makeToast:msg];
                if (isSuccess) {
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self.navigationController popViewControllerAnimated:YES];
                    });
                }
            });
        }];
    }
}
@end
